ark-serialize
defines the CanonicalSerialize
and CanonicalDeserialize
traits for serializing and deserializing Rust data structures to bytes efficiently. The interfaces offered by these traits are specialized for serializing cryptographic objects. In particular, they offer special support for compressed representation of elliptic curve elements.
Most types in arkworks-rs
implement these traits.
Usage
To use ark-serialize
, add the following to your Cargo.toml
:
= "0.4"
If you additionally want to derive implementations of the CanonicalSerialize
and CanonicalDeserialize
traits for your own types, you can enable the derive
feature:
= { = "0.4", = ["derive"] }
Examples
Let us first see how to use ark-serialize
for existing types:
// We'll use the BLS12-381 pairing-friendly group for this example.
use ;
use ;
use UniformRand;
let mut rng = test_rng;
// Let's sample uniformly random group elements:
let a: G1Affine = G1 rand.into;
let b: G2Affine = G2 rand.into;
// We can serialize with compression...
let mut compressed_bytes = Vec new;
a.serialize_compressed.unwrap;
// ...and without:
let mut uncompressed_bytes = Vec new;
a.serialize_uncompressed.unwrap;
// We can reconstruct our points from the compressed serialization...
let a_compressed = deserialize_compressed.unwrap;
// ... and from the uncompressed one:
let a_uncompressed = deserialize_uncompressed.unwrap;
assert_eq!;
assert_eq!;
// If we trust the origin of the serialization
// (eg: if the serialization was stored on authenticated storage),
// then we can skip some validation checks, which can greatly reduce deserialization time.
let a_uncompressed_unchecked = deserialize_uncompressed_unchecked.unwrap;
let a_compressed_unchecked = deserialize_compressed_unchecked.unwrap;
assert_eq!;
assert_eq!;
If we want to serialize our own structs, we can derive implementations of the CanonicalSerialize
and CanonicalDeserialize
traits if all fields implement these traits. For example:
use ;
use ;
We can also implement these traits manually. For example:
use ;
use ;
use ;
// We additionally have to implement the `Valid` trait for our struct.
// This trait specifies how to perform certain validation checks on deserialized types.
// For example, we can check that the deserialized group elements are in the prime-order subgroup.